{% block ubicacion_widget %}
{% spaceless %}
<input type="text" id="addresspicker" class="expand" />
<div id="addresspicker_map" style="width:100%; height:250px;display:none;"></div>
<div id="addresspicker_results" class="custom dropdown expand"></div>

<script type="text/javascript">

    var geocoder = new google.maps.Geocoder();
    var gmap;
    var gmarker;

    function loadMapFromInputs()
    {
        var txtPais = $("#{{ form.parent.vars.id }}_pais").val();
        var txtProvincia = $("#{{ form.parent.vars.id }}_provincia").val();
        var txtLocalidad = $("#{{ form.parent.vars.id }}_localidad").val();
        var txtLat = parseFloat($("#{{ form.parent.vars.id }}_lat").val());
        var txtLng = parseFloat($("#{{ form.parent.vars.id }}_lng").val());

        var arrAddresspicker = new Array();

        if(txtLocalidad)
        {
            arrAddresspicker.push(txtLocalidad);
        }
        if(txtProvincia)
        {
            arrAddresspicker.push(txtProvincia);
        }
        if(txtPais)
        {
            arrAddresspicker.push(txtPais);
        }
        if(arrAddresspicker.length > 0)
        {
            $("#addresspicker").val(arrAddresspicker.join(', '));
        }
        if(txtLat && txtLng)
        {
            var ubicacion = {};
            ubicacion.lat = txtLat;
            ubicacion.lng = txtLng;
            dibujarMapa(ubicacion);
        }
    }

    function dibujarMapa(ubicacion)
    {
        $("#addresspicker_map").show();

        var center = new google.maps.LatLng(ubicacion.lat, ubicacion.lng);
        var mapOptions = {
            center: center,
            zoom: 13,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        gmap = new google.maps.Map(document.getElementById("addresspicker_map"),
                mapOptions);

        var pinColor = "FE7569";
        var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
                new google.maps.Size(21, 34),
                new google.maps.Point(0,0),
                new google.maps.Point(10, 34));
        var pinShadow = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
                new google.maps.Size(40, 37),
                new google.maps.Point(0, 0),
                new google.maps.Point(12, 35));


        gmarker = new google.maps.Marker({
            position: center,
            map: gmap,
            draggable: true,
            icon: pinImage,
            shadow: pinShadow
        });

        google.maps.event.addListener(gmarker, 'dragend', reverseGeocode);

    }

    function getLabel(geocodeResult)
    {
        var ubicacion = parseGeocodeResult(geocodeResult);

        var array = new Array();
        if(ubicacion.country)
        {
            array.push(ubicacion.country);
        }

        if(ubicacion.administrative_area_level_1)
        {
            array.push(ubicacion.administrative_area_level_1);
        }

        if(ubicacion.locality)
        {
            array.push(ubicacion.locality);
        }
        else if(ubicacion.administrative_area_level_2)
        {
            array.push(ubicacion.administrative_area_level_2);
        }
        return array.reverse().join(', ');
    }

    function updateInputs(ubicacion)
    {

        $("#{{ form.parent.vars.id }}_pais").val('');
        $("#{{ form.parent.vars.id }}_provincia").val('');
        $("#{{ form.parent.vars.id }}_localidad").val('');
        $("#{{ form.parent.vars.id }}_lat").val('');
        $("#{{ form.parent.vars.id }}_lng").val('');


        if(ubicacion.country)
        {
            $("#{{ form.parent.vars.id }}_pais").val(ubicacion.country);
        }

        if(ubicacion.administrative_area_level_1)
        {
            $("#{{ form.parent.vars.id }}_provincia").val(ubicacion.administrative_area_level_1);
        }

        if(ubicacion.locality)
        {
            $("#{{ form.parent.vars.id }}_localidad").val(ubicacion.locality);
        }
        else if(ubicacion.administrative_area_level_2)
        {
            $("#{{ form.parent.vars.id }}_localidad").val(ubicacion.administrative_area_level_2);
        }

        if(ubicacion.lat)
        {
            $("#{{ form.parent.vars.id }}_lat").val(ubicacion.lat);
        }

        if(ubicacion.lng)
        {
            $("#{{ form.parent.vars.id }}_lng").val(ubicacion.lng);
        }

        dibujarMapa(ubicacion);

    }

    function reverseGeocode(location)
    {
        geocoder.geocode({'latLng': location.latLng}, $.proxy(function(results, status){
            if (status == google.maps.GeocoderStatus.OK)
            {
                var ubicacion = parseGeocodeResult(results[0]);
                $("#addresspicker").val(getLabel(results[0]));
                updateInputs(ubicacion);
            }
        }, this));
    }

    function parseGeocodeResult(geocodeResult)
    {
        var parsed = {lat: geocodeResult.geometry.location.lat(),
            lng: geocodeResult.geometry.location.lng()};

        var _addressParts= {street_number: null, route: null, locality: null,
            administrative_area_level_2: null, administrative_area_level_1: null,
            country: null, postal_code:null, type: null};

        for (var addressPart in _addressParts){
            parsed[addressPart] = findInfo(geocodeResult, addressPart);
        }

        parsed.type = geocodeResult.types[0];
        return parsed;
    }

    function findInfo(result, type)
    {
        for (var i = 0; i < result.address_components.length; i++) {
            var component = result.address_components[i];
            if (component.types.indexOf(type) !=-1) {
                return component.long_name;
            }
        }
        return false;
    }


    $(function() {

        $( "#addresspicker" ).autocomplete({
            appendTo: '#addresspicker_results',
            delay: 700,
            source: function( request, response ) {
                var address = request.term, self = this;
                geocoder.geocode({
                    'address': address
                }, function(results, status) {
                    if (status == google.maps.GeocoderStatus.OK && results) {
                        for (var i = 0; i < results.length; i++) {
                            results[i].label = getLabel(results[i]);
                        }
                    }
                    response(results);
                })
            },
            search: function() {
                // custom minLength
                var term = this.value;
                if ( term.length < 2 ) {
                    return false;
                }
            },
            select: function( event, ui ) {
                var ubicacion = parseGeocodeResult(ui.item);
                updateInputs(ubicacion);

            }
        });
    });

</script>

{% endspaceless %}
{% endblock %}